propsage.namespace('modules.admin.users');

modules.admin.users.adduser = (function($, ui) {
	function initEventHandlers() {
		$('#btnSearchCEADatabase').on('click', onBtnSearchCEADatabaseClick);
		$('#btnRandomPassword').on('click', onBtnRandomPasswordClick);
	}
	
	function onBtnRandomPasswordClick(e) {
		e.preventDefault;
		var randomPassword = generateRandomPassword();
		
		$('#User_password').val(randomPassword);
	}
	
	function generateRandomPassword(plength) {
		plength = plength || 6;
		
		var keylist="0123456789";
		var temp='';
		
		for (var i=0; i<plength; i++) {
			temp += keylist.charAt(Math.floor(Math.random()*keylist.length))
		}
		
		return temp;
	}
	
	function onBtnSearchCEADatabaseClick(e) {
		e.preventDefault();
		
		var licenseNo = $('#User_license_no').val();
		
		if (licenseNo == '') {
			window.alert('Please enter the CEA license no');
		} else {
			var href = baseUrl + '/admin/users/ajaxSearchCEADatabase';
			var data = {
				license_no: licenseNo
			};
			
			$('#btnSearchCEADatabase').prop('disabled', true);
			ui.doAjax('GET', href, data, onSearchCEADatabaseSuccess, onSearchCEADatabaseFailure);
		}
	}
	
	function onSearchCEADatabaseSuccess(response) {
		$('#btnSearchCEADatabase').prop('disabled', false);
		if (response.result == 'success') {
			var data = response.data;
			
			$.each(data, function(key, value) {
				$('#User_' + key).val(value);
			});
		}
	}
	
	function onSearchCEADatabaseFailure() {
		$('#btnSearchCEADatabase').prop('disabled', false);
	}
	
	$(document).ready(function() {
		initEventHandlers();
	});
})(jQuery, propsage.ui);